﻿using Spire.Pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;
using File = System.IO.File;

namespace SuperKit
{
    class PDFPageCounter : CommandExecutor {
        List<FileInfo> list;
        int currentIndex = 0;

        public PDFPageCounter(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
        }

        public override void Execute() {
            DirectoryInfo info = new DirectoryInfo(FilePath);
            list = new List<FileInfo>();
            GetAllFiles(info, list, Kit.PDF_EXTS);

            var t = new Thread(OnProcess);
            t.Start();
        }

        private void OnProcess() {
            currentIndex = 0;
            foreach (var i in list) {
                Process(i);
                currentIndex++;
            }

            End();
        }

        private void Process(FileInfo f) {
            PdfDocument doc = new PdfDocument(f.FullName);
            int pages = doc.Pages.Count;
            doc.Close();

            var pure = Path.GetFileNameWithoutExtension(f.Name);
            var newName = string.Format("{0}[{1}P].pdf", RemovePageText(pure), pages);
            var newPath = Path.Combine(f.DirectoryName, newName);

            if (File.Exists(newPath)) {
                Flush("同名项目已经存在：{0}", newPath);
                return;
            }
            try {
                File.Move(f.FullName, newPath);
                SetStatus($"成功改名({currentIndex + 1}/{list.Count})：{newPath}");
            } catch (IOException e) {
                Flush(e.Message);
            }
        }


        public static string RemovePageText(string s) {
            Regex r = new Regex("\\[[0-9]+P\\]");
            string newName = s;
            if (r.IsMatch(s)) {
                newName = r.Replace(s, "");
            }
            return newName;
        }


    }
}
